<script lang="ts">
export default {
  name: 'admin-user'
};
</script>

<script setup lang="ts">
import { reactive, ref, onMounted, toRefs } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import {
  userAdminApi,
  stateAdminApi,
  authorityApi,
  authorityUserApi,
  shareAuthorityApi,
  addRoleApi,
  uploadRoleApi,
  delRoleApi
} from '@/api/user';
import { ElForm, ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';

import SingleUpload from '@/components/Upload/SingleUpload.vue';
const state = reactive({
  uid: '',
  ids: [],
  loading: false,
  userList: [],
  query: {
    phone: '',
    pageNumber: 1,
    pageSize: 5,
    total: 0
  },
  resourceOptions: []
});
const queryParams = reactive({
  keywords: '',
  status: ''
});

const queryFormRef = ref(ElForm); // 查询表单

const init = async () => {
  state.loading = true;
  const { data } = await userAdminApi({
    page: state.query.pageNumber,
    size: state.query.pageSize,
    state: queryParams.status,
    phone: queryParams.keywords
  });
  state.userList = data.data;
  state.query.total = data.pageable.total;
  state.loading = false;
};

const handleStatusChange = async (row: any) => {
  await stateAdminApi({ uid: row.uid });
  init();
};

// 重置
const resetQuery = () => {
  queryFormRef.value.resetFields();
  init();
};
// * 页码改变
const pageChange = (page: number) => {
  state.query.pageNumber = page;
  init();
};

// * 每页条数改变
const sizeChange = (size: number) => {
  state.query.pageNumber = 1;
  state.query.pageSize = size;
  init();
};
onMounted(() => {
  init();
  authority();
});

const dialog = reactive({
  visible: false
});

const formData = reactive({
  phone: '',
  state: '0',
  password: '',
  photo: ''
});

const formRef = ref({
  phone: [{ required: true, message: '请输入角色手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入角色密码', trigger: 'blur' }],
  state: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  photo: [{ required: true, message: '请上传头像', trigger: 'blur' }]
});

const formUploadData = reactive({
  userName: '',
  password: '',
  photo: '',
  uid: ''
});

const formUploadRef = reactive({
  userName: [{ required: true, message: '请输入角色昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入角色密码', trigger: 'blur' }],
  photo: [{ required: true, message: '请上传头像', trigger: 'blur' }]
});

const closeDialog = () => {
  dialog.visible = false;
  dataFormRef.value.resetFields();
};

const dataFormRef = ref(ElForm);
const dataUploadFormRef = ref(ElForm);

// 新增角色
const submitForm = async () => {
  await dataFormRef.value.validate();
  await addRoleApi(formData);
  ElMessage.success('新增成功');
  dialog.visible = false;
  init();
};

// 获取所有权限
const authority = async () => {
  const { data } = await authorityApi();
  state.resourceOptions = data;
};
// 权限dialog
const allocationDialogVisible = ref(false);
const resourceRef = ref(ElTree);
const showAllocationDialog = async (row: any) => {
  state.uid = row.uid;
  allocationDialogVisible.value = true;
  const { data } = await authorityUserApi({ uid: row.uid });
  data.forEach((item: any) => resourceRef.value.setChecked(item, true));
};
const handleAllocationSubmit = async () => {
  const checkedMenuIds = resourceRef.value
    .getCheckedNodes(false, true)
    .map((node: any) => node.value);
  await shareAuthorityApi({ uid: state.uid, roles: checkedMenuIds });
  ElMessage.success('分配成功');
  allocationDialogVisible.value = false;
};

const closeAllocationDialog = () => {
  allocationDialogVisible.value = false;
};
const addRole = () => {
  dialog.visible = true;
};

const uploadVisible = ref(false);
const uploadInfo = (row: any) => {
  uploadVisible.value = true;
  formUploadData.photo = row.photo;
  formUploadData.uid = row.uid;
  formUploadData.password = row.password;
  formUploadData.userName = row.userName;
};
// 关闭修改用户信息dialog
const closeUploadDialog = () => {
  uploadVisible.value = false;
  dataUploadFormRef.value.resetFields();
};
const submitUploadForm = async () => {
  await dataUploadFormRef.value.validate();
  await uploadRoleApi(formUploadData);
  ElMessage.success('修改用户信息成功');
  uploadVisible.value = false;
  init();
};
const handleSelectionChange = async (selection: any) => {
  state.ids = selection.map((item: any) => item.uid);
};
const delRole = async () => {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delRoleApi({ uid: state.ids });
      ElMessage.success('删除成功');
      state.query.pageNumber =
        state.userList.length > 1
          ? state.query.pageNumber
          : state.query.pageNumber - 1;
      init();
    })
    .catch(() => ElMessage.info('已取消删除'));
};
const { loading, userList, resourceOptions } = toRefs(state);
</script>
<template>
  <div class="app-container">
    <!-- 用户数据 -->
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            style="width: 200px"
          >
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="init"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card class="box-card" shadow="never">
      <template #header>
        <el-form-item style="float: left">
          <el-button
            v-hasPerm="['increase']"
            type="success"
            @click="addRole"
            :icon="Plus"
            >新增角色</el-button
          >
        </el-form-item>
        <el-form-item style="float: right">
          <el-button
            type="danger"
            v-hasPerm="['remove']"
            :disabled="!state.ids.length"
            :icon="Delete"
            @click="delRole"
            >删除</el-button
          >
        </el-form-item>
      </template>
      <el-table
        :data="userList"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" align="center" width="100" />
        <el-table-column
          label="手机号码"
          align="center"
          prop="phone"
          width="160"
        />
        <el-table-column
          label="用户昵称"
          width="120"
          align="center"
          prop="userName"
        />
        <el-table-column label="头像" align="center" width="140">
          <template #default="scope">
            <el-image
              :src="scope.row.photo"
              style="width: 60px; height: 60px; border-radius: 50%"
            />
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="state" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.state"
              :inactive-value="'0'"
              :active-value="'1'"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left">
          <template #default="scope">
            <el-button
              :disabled="scope.row.userName == 'admin'"
              :type="scope.row.state === '1' ? 'success' : 'danger'"
              link
              @click="handleStatusChange(scope.row)"
              >{{ scope.row.state === '1' ? '启用' : '禁用' }}
            </el-button>
            <el-button
              v-hasPerm="['distribution']"
              :disabled="scope.row.userName == 'admin'"
              type="success"
              @click="showAllocationDialog(scope.row)"
              link
            >
              资源分配
            </el-button>
            <el-button
              v-hasPerm="['user']"
              :disabled="scope.row.userName == 'admin'"
              type="success"
              @click="uploadInfo(scope.row)"
              link
            >
              修改信息
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-if="userList.length"
        :pageable="state.query"
        @page-change="pageChange"
        @size-change="sizeChange"
      />
    </el-card>
    <el-dialog
      title="新增角色"
      v-model="dialog.visible"
      width="600px"
      @close="closeDialog"
      label-width="100px"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="formRef"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="角色手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入角色手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色密码" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="请输入角色昵称"
            type="password"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色头像" prop="photo">
          <SingleUpload v-model="formData.photo" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="修改用户信息"
      v-model="uploadVisible"
      width="600px"
      @close="closeUploadDialog"
      label-width="100px"
    >
      <el-form
        ref="dataUploadFormRef"
        :model="formUploadData"
        :rules="formUploadRef"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="修改角色昵称" prop="userName">
          <el-input
            v-model="formUploadData.userName"
            clearable
            placeholder="请输入角色昵称"
          />
        </el-form-item>
        <el-form-item label="修改角色密码" prop="password">
          <el-input
            v-model="formUploadData.password"
            type="password"
            clearable
            placeholder="请输入角色密码"
          />
        </el-form-item>
        <el-form-item label="修改角色头像" prop="photo">
          <SingleUpload v-model="formUploadData.photo" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUploadForm">确 定</el-button>
          <el-button @click="closeUploadDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="资源分配" v-model="allocationDialogVisible" width="800px">
      <el-scrollbar max-height="600px" v-loading="loading">
        <el-tree
          ref="resourceRef"
          node-key="value"
          show-checkbox
          :data="resourceOptions"
          :default-expand-all="true"
        >
          <template #default="{ data }">
            {{ data.label }}
          </template>
        </el-tree>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAllocationSubmit"
            >确 定</el-button
          >
          <el-button @click="closeAllocationDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
::v-deep(.el-form-item__label) {
  width: 100px !important;
}
</style>
